﻿using Microsoft.AspNetCore.Http;

namespace Blog.Core.DTO.Helper
{
    public static class PicHelper//图片静态类
    {
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static ResponseResultDTO<dynamic> UpLoad(IFormFile file)
        {
            //统一返回值
            ResponseResultDTO<dynamic> result = new ResponseResultDTO<dynamic>();
            //判断是否选择文件
            if(file==null)
            {
                result.Code = ResultStatusCode.PARAMSERROR;
                result.Message = "请选择文件";
                return result;
            }
            //判断文件内容是否存在
            if (file.Length==0)
            {
                result.Code = ResultStatusCode.PARAMSERROR;
                result.Message = "请选择正确的文件";
                return result;
            }
            //判断文件内容不得大于2M
            if (file.Length >2*1024*1024)
            {
                result.Code = ResultStatusCode.PARAMSERROR;
                result.Message = "请选择文件小于2M";
                return result;
            }
            //判断文件格式是否是图片
            if (!file.ContentType.StartsWith("image/"))
            {
                result.Code = ResultStatusCode.PARAMSERROR;
                result.Message = "请选择图片格式的文件";
                return result;
            }
            var dateStr = DateTime.Now.ToString("yyyy-MM-dd");
            //判断该路径是否存在
            if(!Directory.Exists("wwwroot/Image/"+dateStr))
            {
                //不存在则创建
                Directory.CreateDirectory("wwwroot/Image/" + dateStr);
            }
            //新的图片名称为小写
            var newName=Guid.NewGuid().ToString()+Path.GetExtension(file.FileName).ToLower();
            //图片生成的路径
            var path = "wwwroot/Image/" + dateStr + "/" + newName;
            //判断该路径是否存在
            if(System.IO.File.Exists(path))
            {
                //若存在则提示错误
                result.Code = ResultStatusCode.HANDLEFAIL;
                result.Message = "服务器错误，请稍后重试";
                return result;
            }
            using (FileStream fs=new FileStream(path,FileMode.Create))
            {
                file.CopyTo(fs);//拷贝数据流
                fs.Close();//关闭数据流
            }
            result.Code = ResultStatusCode.SUCCESS;
            result.Message = "图片上传成功";
            result.Data = dateStr + "/" + newName;
            return result;

        }
    }
}